/* eslint-disable require-yield */
/*
 * @Author: Yonyou
 * @Date: 2020-03-11 11:10:28
 * @LastEditTime: 2020-09-15 14:41:10
 * @LastEditors: hanfengmi
 * @Description: 全局数据store
 */
import { 
  GetInfo,
  GetTocken,
  Maidian
} from '@/service/user'
import router from 'umi/router'
import { stringify } from 'qs'
import { getUrlKey } from '@/utils/index'
import maidianInfo from '@/utils/burypoint'

export default {
  namespace: 'user',
  state: {
    name: 'xixi',
    beforeInTime: '',
    info: null,
    beforeUrl: ''
  },
  subscriptions: {
    setup({dispatch, history }) {
      const ciId = getUrlKey('ciId') // 获取url中ciId
      history.listen((location) => {
        // 跳转路由时将入口带的ciId随时携带
        if(!location.query.ciId) {
          history.replace(location.pathname + `?${stringify({ ...location.query, ciId})}`)
        }else {
          // 埋点信息
          dispatch({
            type: 'maidian',
            payload: {
              url: window.location.href
            }
          })
          dispatch({
            type: 'NeedLogin',
            payload: {
              pathname: location.pathname
            }
          })
          window.onbeforeunload = ()=> { // 关闭页面埋点 
            dispatch({
              type: 'save',
              payload: {
                beforeUrl: window.location.href
              }
            })
            dispatch({
              type: 'maidian',
              payload: {
                url: window.location.href
              }
            })
            
          }
        }
        // 跳转路由页面重置顶部
        document.getElementsByTagName('html')[0].scrollTop = 0
      })
    }
  },
  effects: {
    *NeedLogin({ payload }) {
      // 不需要登陆可直接查看到页面
      const { pathname } = payload
      if(pathname === '/login') return false
      if(pathname === '/login/register') return false
      
      if(pathname === '/case') return false
      if(pathname === '/title') return false
      // ! 跳转外部登录
      // loginOut('login')
      // !跳转内部登录
      router.push('/case')
    },
    *maidian({ payload }, { call,put,select }) {
      const { beforeUrl,beforeInTime, info } = yield select(({ user }) => user)
      let time = new Date().getTime()
      if(beforeUrl) {
        yield call(Maidian, `&url=${escape(beforeUrl)}&lt=${beforeInTime}&ot=${time}${maidianInfo}&user_id=${info && info.encUserId}`)
      }
      yield put({
        type: 'save',
        payload: {
          beforeUrl: payload.url,
          beforeInTime: time
        }
      })
    },
    // 获取tocken
    *GetTocken({ payload,callback }, { call }) {
      const response = yield call(GetTocken, payload)
      if(response.Success) {
        localStorage.setItem('fwq-auth-token',response.Data.access_token)
        callback && callback()
        setTimeout(()=>{
          window.g_app._store.dispatch({ // 用户第一次进入
            type: 'user/GetTocken',
            payload: {
              user_id: payload.user_id,
              ciId: payload.ciId
            }
          })
        },3000 * 1000)
      }
    },
    // 缓存获取用户信息
    *GetInfo({ payload,callback }, { call, put }) {
      const response = yield call(GetInfo, payload)
      if(response.Success) {
        if(!response.Data.user_baseinfo) { // 未登录
          localStorage.removeItem('fwq-auth-token')
          localStorage.removeItem('fwq-user-info')
          return false
        }
        yield put({
          type: 'save',
          payload: {
            info: response.Data.user_baseinfo
          }
        })
        const fwq_user = { 
          encUserId: response.Data.user_baseinfo.encUserId, 
          encCiId: response.Data.user_baseinfo.encCiId,
          userId: response.Data.user_baseinfo.userId, 
          ciId: response.Data.user_baseinfo.ciId
        }
        localStorage.setItem('fwq-auth-token',response.Data.token)
        localStorage.setItem('fwq-user-info',JSON.stringify(fwq_user))
        setTimeout(()=>{
          window.g_app._store.dispatch({ // 用户第一次进入
            type: 'user/GetTocken',
            payload: {
              user_id: response.Data.user_baseinfo.userId,
              ciId: response.Data.user_baseinfo.ciId
            }
          })
        },3000 * 1000)
        callback && callback()
      }else { // 登陆失败-》tocken 获取失败
        localStorage.removeItem('fwq-auth-token')
        localStorage.removeItem('fwq-user-info')
      }
      callback && callback()
    }
  },

  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        ...payload
      }
    }
  }
}
  